
var app = getApp()

// ArrayBuffer转16进度字符串示例
function ab2hex(buffer) {
  var hexArr = Array.prototype.map.call(
    new Uint8Array(buffer),
    function (bit) {
      return ('00' + bit.toString(16)).slice(-2)+" "
    }
  )
  return (hexArr.join('')).toUpperCase();
}

function stringToBytes(str) {
  var ch, st, re = [];
  for (var i = 0; i < str.length; i++) {
    ch = str.charCodeAt(i);  // get char  
    st = [];                 // set up "stack"  
    do {
      st.push(ch & 0xFF);  // push byte to stack  
      ch = ch >> 8;          // shift value down by 1 byte  
    }
    while (ch);
    // add stack contents to result  
    // done because chars have "wrong" endianness  
    re = re.concat(st.reverse());
  }
  // return an array of bytes  
  return re;
}

function onSend(sendContent){
  var strbuf = new Uint8Array(stringToBytes(sendContent))
  var buffer1 = strbuf.buffer
  // console.log("strtobyte ", strbuf)
  // console.log("Txbuf = ",buffer1)
  if (buffer1==null)return
  const txlen = buffer1.byteLength
  wx.writeBLECharacteristicValue({
    deviceId: app.globalData.deviceId,
    serviceId: app.globalData.serviceId,
    characteristicId: app.globalData.characteristicId,
    value: buffer1,
    success: function (res) {
      // success
      // console.log("指令发送成功 ", sendContent);
    },
    fail: function (res) {
      // fail
      console.error(res);
    },
    complete: function (res) {
      // complete
    }
  })
}

module.exports = {
  onSend: onSend
}